<?php

namespace app\admin\controller;

use think\facade\Db;
use think\facade\View;
use think\Request;
use app\common\controller\Common;
use app\admin\validate\ChatsValidate;

class Chats extends Common
{
    /**
     * 主页
     */
    public function index()
    {
        $customerpay = get_addons_instance('customerpay');
        if (!empty($customerpay) && $customerpay->getInfo()['state'] == 1 && $customerpay->getConfig(0, 1)['status'] == 1) $customerpay = 1;
        else $customerpay = 0;

        View::assign('customerpay', $customerpay);

        return view();
    }

    /**
     * 添加快捷回复分组
     */
    public function addGroup(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $data = $r->post();
            $validate = new ChatsValidate();

            if (!$validate->scene('addGroup')->check($data)) {
                return json(['code' => 300, 'data' => $validate->getError()]);
            }

            $cuid = $this->custs['id'];
            // 查询是否有重名
            $is_group_name = Db::name('im_fastreply_group')->where([
                'name' => $data['group_name'],
                'cuid' => $cuid
            ])->count();
            if (!$is_group_name) {
                $group_id = Db::name('im_fastreply_group')->insertGetId([
                    'name' => $data['group_name'],
                    'add_time' => time(),
                    'cuid' => $cuid
                ]);
                return json(['code' => 200, 'data' => '添加成功', 'group_id' => $group_id]);
            } else {
                return json(['code' => 300, 'data' => '您已经添加过该名称']);
            }
        }
    }

    /**
     * 添加快捷回复
     */
    public function addReply(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $data = $r->post();
            $validate = new ChatsValidate();

            if (!$validate->scene('addReply')->check($data)) {
                return json(['code' => 300, 'data' => $validate->getError()]);
            }

            $cuid = $this->custs['id'];
            // 查询是否有重名
            $is_reply_name = Db::name('im_fastreply')->where([
                'title' => $data['reply_title'],
                'group_id' => $data['group_id'],
                'cuid' => $cuid
            ])->count();
            if (!$is_reply_name) {
                Db::name('im_fastreply')->insert([
                    'title' => $data['reply_title'],
                    'group_id' => $data['group_id'],
                    'content' => $data['reply_content'],
                    'add_time' => time(),
                    'cuid' => $cuid
                ]);
                return json(['code' => 200, 'data' => '添加成功']);
            } else {
                return json(['code' => 300, 'data' => '您已经添加过该名称']);
            }
        }
    }

    /**
     * 修改快捷回复分组
     */
    public function editGroup(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $data = $r->post();
            $validate = new ChatsValidate();

            if (!$validate->scene('addGroup')->check($data)) {
                return json(['code' => 300, 'data' => $validate->getError()]);
            }

            Db::name('im_fastreply_group')->update([
                'id' => $data['group_id'],
                'name' => $data['group_name'],
                'cuid' => $this->custs['id']
            ]);
            return json(['code' => 200, 'data' => '修改成功']);
        }
    }

    /**
     * 修改快捷回复
     */
    public function editReply(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $data = $r->post();
            $validate = new ChatsValidate();

            if (!$validate->scene('addReply')->check($data)) {
                return json(['code' => 300, 'data' => $validate->getError()]);
            }

            Db::name('im_fastreply')->update([
                'id' => $data['reply_id'],
                'title' => $data['reply_title'],
                'group_id' => $data['group_id'],
                'content' => $data['reply_content'],
                'cuid' => $this->custs['id']
            ]);
            return json(['code' => 200, 'data' => '修改成功']);
        }
    }

    /**
     * 更新游客信息
     */
    public function updateVisitors(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $data = $r->post();
            if (in_array($data['key'], ['name', 'phone', 'note'])
                && !empty($data['vinid'])) {
                Db::name('im_visitors_info')->update([
                    'id' => intval($data['vinid']),
                    $data['key'] => $data['val'],
                    'cuid' => $this->main_id
                ]);
            }
            return json(['code' => 200, 'data' => '修改成功']);
        }
    }

    /**
     * 加入黑名单
     */
    public function joinBlacklist(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $data = [
                'cuid' => $this->main_id,
                'vsid' => $r->post('curvsid', 0, 'intval')
            ];
            $black = Db::name('im_blacklist')->where($data)->count();
            if (empty($black)) {
                $data['add_time'] = time();
                Db::name('im_blacklist')->insert($data);
            }
            unset($data['add_time']);
            Db::name('im_dialogue')->where($data)->update(['isshow' => 0]);
            return json(['code' => 200, 'data' => '已加入黑名单']);
        }
    }

    /**
     * 移除黑名单
     */
    public function delBlacklist(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            Db::name('im_blacklist')->where([
                'id' => $r->post('blid', 0, 'intval'),
                'cuid' => $this->main_id
            ])->delete();
            Db::name('im_dialogue')->where([
                'isshow' => 0,
                'cuid' => $this->main_id,
                'vsid' => $r->post('vsid', 0, 'intval')
            ])->update(['isshow' => 1]);
            return json(['code' => 200, 'data' => '已移除黑名单']);
        }
    }

    /**
     * 更改客服状态
     */
    public function updateCustomerState(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $state = $r->post('state', 0, 'intval');
            Db::name('im_customer')->save([
                'id' => $this->custs['id'],
                'state' => $state
            ]);
            return json(['code' => 200]);
        }
    }

    /**
     * 单个游客聊天记录页面展示
     */
    public function onehistory()
    {
        return view();
    }

    /**
     * @param Request $r
     * 转接客服
     */
    public function transfer(Request $r){

        if ($r->isAjax() && $r->isPost()) {
            $vsid = $r->post('vsid', 0, 'intval');
            $kfid = $r->post('kfid', 0, 'intval');

            // 转移当前会话到新的客服
            // 如果新的客服
            $isDialogue = Db::name('im_dialogue')->where([
                'cuid' => $kfid,
                'vsid' => $vsid
            ])->findOrEmpty();

            if( $isDialogue ){
                $result = Db::name('im_dialogue')->where([
                    'cuid' => $this->custs['id'],
                    'vsid' => $vsid
                ])->delete();
            }else{
                $result = Db::name('im_dialogue')->where([
                    'cuid' => $this->custs['id'],
                    'vsid' => $vsid
                ])->data(['cuid' => $kfid])
                    ->update();
            }

            // 访客信息转移
            DB::name('im_visitors_info')
                ->data(['cuid'=>$kfid])
                ->where([
                    'cuid'=> $this->custs['id'],
                    'vsid'=> $vsid
                ])->update();

            // 转移聊天记录到新的客服
            Db::name('im_record')
                ->where("send = {$vsid} AND receive = {$this->custs['id']}")
                ->whereOr("send = {$this->custs['id']} AND receive = {$vsid}")
                ->data([
                    'send'=>Db::raw('CASE `send` WHEN '.$this->custs['id'].' THEN '.$kfid.' ELSE `send` END '),
                    'receive' =>Db::raw('CASE `receive` WHEN '.$this->custs['id'].' THEN '.$kfid.' ELSE `receive` END')
                ])
                ->update();

             /*   print_r(DB::getLastSql());
                return json(['code' => 300, 'data' => '失败']);
            }*/

            return json(['code' => 200, 'data' => '转接成功']);
        }

    }

    /**
     * 删除对话
     */
    public function delDialogue(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $isdelete = Db::name('im_dialogue')->where([
                'cuid' => $this->custs['id'],
                'vsid' => $r->post('vsid', 0, 'intval')
            ])->delete();
            if ($isdelete) {
                return json(['code' => 200, 'data' => '转接成功']);
            } else {
                return json(['code' => 300, 'data' => '转接失败']);
            }
        }
    }
}
